package com.cqie.secondhandtransaction.DTO;

import com.cqie.secondhandtransaction.entity.UserInfo;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.io.Serializable;
import java.util.*;

@Data
@NoArgsConstructor
public class UserDetailsDTO implements UserDetails, Serializable {

    private int id;

    private String username;

    private String password;

    private String phone;

    private Integer role;

    private Integer productId;

    private String address;

    private String picture;

    private String soldNum;

    private Date createTime;

    private Date updateTime;

    /** token */
    private String token;

    private  Set<GrantedAuthority> authorities;

    public UserDetailsDTO(String username, String password, Collection<? extends GrantedAuthority> authorities, UserInfo userInfo) {
        if(Objects.nonNull(userInfo)){
            BeanUtils.copyProperties(userInfo, this);
        }
        this.username = username;
        this.authorities = Collections.unmodifiableSet(new HashSet<>(authorities));
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return this.authorities;
    }

    @Override
    public String getUsername() {
        return this.username;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }

    public UserInfo toUserInfo(){
        UserInfo userInfo = new UserInfo();
        BeanUtils.copyProperties(this, userInfo);
        return userInfo;
    }
}
